<?php

namespace app\api\controller;

use app\api\controller\Tpmecms;
use think\Db;

/**
 * 发送接口
 */
class Send extends Tpmecms
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 发送微信模版消息
     *
     * @param string $appid appid
     * @param string $secret 密钥
     * @param string $title 标题
     * @param string $content 需要发送的内容
     * @return void
     */
    public function wx_template($appid=null,$secret=null,$title=null,$content=null)
    {
        $user = Db::name('user')->where('app_id',$appid)->where('key',$secret)->find();
        if(!$user){
            $this->error('app_id和密钥不正确');
        }
        $data['title'] = $title??'标题';
        $data['content'] = $content??'接口调试成功';
        $data['uid'] = $user['id'];
        $data['time'] = time();
       
        $data['id'] = Db::name('msg')->insertGetId($data);
        $this->send_user($user['wx_openid'],$data);

    }


   
     /**
     * 发送微信模版消息给用户
     * @ApiInternal()
     *
     * @param string $openid 微信公众号openid
     * @param string $data 数组
     * @return void
     */    
    public function send_user($openid='oequ652m7_N6H0eQkn7sUz66QtXw',$data)
    {
        $content = $data['content'];
        $app = $this->get_wx_gzh_app();
        $res = $app->template_message->getPrivateTemplates();
        $list = $res['template_list'];
        // halt($list);
        if(sizeof($list)<1){
            $this->error('还未添加模版哦');
        }
        $template = $list[0];
        
        $msg_res = $app->template_message->send([
            'touser' => $openid,
            'template_id' => '7KQR0JnS0UjgKyQ1tdAE3NPoJxNpUyyF3cIzEqGgpdA',
            'url' => 'http://wechat.rsws.top/cms/wechat/msg?id='.base64_encode($data['id']),
            'data' => [
                //{{first.DATA}}\n通知内容：{{keyword1.DATA}}\n通知时间：{{keyword2.DATA}}\n{{remark.DATA}}
                'first' => $data['title'],
                 'keyword1' => '本文内容由您自行调用接口发送，点击【本页】查看,如果非本人调用，请与管理员联系。'
                 'keyword2'=> date('Y-m-d H:i:s'),
                 'remark'=> '备注',
                 
                
            ],
        ]);
        if($msg_res['errcode']>0 || $msg_res['errmsg']!='ok'){
            $this->error('(是否关注微信公众号了？)发送失败:'.$msg_res['errmsg']);
        }else {
            $this->success('ok');
        }

    }

}
